import indexConfig from "../config/index.config.js"

export default {
    /* 
     * 时间格式化
     * date:日期
     * 格式：00年00月00日
     */
    formatTime(formatNumber) {
        let arr = formatNumber.split(' ');
        let ymd = arr[0].split('-');
        return ymd[0] + "年" + ymd[1] + "月" + ymd[2] + "日"
    },

    /* 
     * 时间格式化
     * date:日期
     * 格式：00年00月00日
     */
    formatTimeMD(formatNumber) {
        if (formatNumber != undefined) {
            let arr = formatNumber.split(' ');
            let ymd = arr[0].split('-');
            let times = arr[1].split(':');
            var date = new Date;
            var year = date.getFullYear();
            if (year != ymd[0]) {
                return ymd[0] + "年" + ymd[1] + "月" + ymd[2] + "日 " + times[0] + ":" + times[1]
            } else {
                return ymd[1] + "月" + ymd[2] + "日 " + times[0] + ":" + times[1]
            }

        } else {
            return '';
        }
    },

    /*
    获取当前年月日时分秒
    */
    getDateTime() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        month = month < 10 ? "0" + month : month;
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    },

    /* 
     * 将cityNo 转 cityName
     * cityData:原数据
     * cityNo：二级地区编码
     */
    getCityName(cityData, cityNo) {
        if (!cityNo) return;
        if (!(cityData instanceof Array)) return;
        // 9112
        cityNo += "";
        for (let i = 0; i < cityData.length; i++) {
            let sheng = cityData[i];
            for (let j = 0; j < sheng.children.length; j++) {
                let shi = sheng.children[j];
                if (shi.value == cityNo) {
                    // 使用return 终止循环
                    return `${sheng.label}-${shi.label}`;
                }
            }
        }
    },

    /* 
     * obj 转 params字符串参数  
     * 例子：{a:1,b:2} => a=1&b=2
     */
    objParseParam(obj) {
        let paramsStr = "";
        if (obj instanceof Array) return paramsStr;
        if (!(obj instanceof Object)) return paramsStr;
        for (let key in obj) {
            paramsStr += `${key}=${obj[key]}&`;
        }
        return paramsStr.substring(0, paramsStr.length - 1);
    },

    /* 
     * obj 转 路由地址带参数
     * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
     */
    objParseUrlAndParam(path, obj) {
        let url = path || "/";
        let paramsStr = "";
        if (obj instanceof Array) return url;
        if (!(obj instanceof Object)) return url;
        paramsStr = this.objParseParam(obj);
        paramsStr && (url += "?");
        url += paramsStr;
        return url;
    },

    /* 
     * 获取url字符串参数
     */
    getRequestParameters(locationhref) {
        let href = locationhref || "";
        let theRequest = new Object();
        let str = href.split("?")[1];
        if (str != undefined) {
            let strs = str.split("&");
            for (let i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }
        return theRequest;
    },

    /* 
     * 银行卡每四位空格
     */
    formatCardNo(cardNo) {
        cardNo += "";
        return cardNo.replace(/\s/g, '').replace(/[^\d]/g, '').replace(/(\d{4})(?=\d)/g, '$1 ');
    },

    /**
     * 乘法，解决js精度损失问题
     * @param {*} arg1 
     * @param {*} arg2 
     */
    accMul(arg1, arg2) {
        arg1 = arg1 || 0;
        var m = 0,
            s1 = arg1.toString(),
            s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length
        } catch (e) {}
        try {
            m += s2.split(".")[1].length
        } catch (e) {}
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
    },

    /*
     * 将一个数组分成几个同等长度的数组
     * array[分割的原数组]
     * size[每个子数组的长度]
     */
    sliceArray(array, size) {
        var result = [];
        for (var x = 0; x < Math.ceil(array.length / size); x++) {
            var start = x * size;
            var end = start + size;
            result.push(array.slice(start, end));
        }
        return result;
    },

    /*
     * 计算两个时间差小时数
     * sDate1[结束时间]
     * sDate2[开始时间]
     */
    calcDate(start, end) {
        if (!start || !end) {
            return 0;
        }
        var d1 = new Date(start);
        var d2 = new Date(end);
        var hours = Math.floor(parseInt(d2 - d1) / 1000 / 60 / 60);
        var mins = Math.floor(parseInt(d2 - d1) / 1000 / 60 % 60);
        var hoursTemp = 0;

        if (mins < 15) {
            hoursTemp = 0;
        } else if (mins >= 15 && mins < 30) {
            hoursTemp = 0.5;
        } else if (mins >= 30 && mins < 45) {
            hoursTemp = 0.5;
        } else if (mins >= 45) {
            hoursTemp = 1;
        }
        hours = hours + hoursTemp;
        return hours;
    },

    /*二维数组获取数组中某一列的全部内容*/
    array_column(arr, column) {
        return arr.map(x => x[column])
    },

    /*一维数组去重*/
    array_unique(arr) {
        return [...new Set(arr)];
    },

    /*
     *二维数组去重
     *array_unique_two_dimensional(matrix);
     */
    array_unique_two_dimensional(arr) {
        var obj = {};
        for (var i = 0; i < arr.length; i++) {
            // 判断当前项是否遍历过，是则删除，否存入obj以作对照
            if (obj.hasOwnProperty(arr[i])) {
                arr.splice(i, 1)
                i++;
            }
            obj[arr[i]] = i;
        }
        return arr;
    },

    /**
     * array_unique_two_dimensional(arr,'name');
     */
    array_unique_two_dimensional(arr, param = '') {
        const res = new Map();
        return arr.filter((a) => !res.has(a[param]) && res.set(a[param], 1))
    },

    handleHongbao(data) {
        let hongbaoQueue = JSON.parse(uni.getStorageSync('hongBaoQueur') || '[]')

        if (!data) {
            if (hongbaoQueue.length === 0) {
                return false
            }

            const hongbao = hongbaoQueue.shift()

            uni.setStorageSync('hongBaoQueur', JSON.stringify(hongbaoQueue))

            return hongbao
        }

        hongbaoQueue.push(data)

        uni.setStorageSync('hongBaoQueur', JSON.stringify(hongbaoQueue))

    },

    handleHongbaoStatus(status) {
        const flag = 'hongbaoStatus'

        if (!status) {
            const hongbaoStatus = uni.getStorageSync(flag) || 'false'

            console.log('hongb ', hongbaoStatus)

            return hongbaoStatus === 'true'
        }


        uni.setStorageSync(flag, status)

    },

    handleUnReadMsg(keys, value) {
        // 获取用户id
        const userId = uni.getStorageSync('userInfo').id

        const msgkey = `unReadMsg-${userId}`

        let msg = uni.getStorageSync(msgkey) || {
            length: 0
        }

        msg = typeof msg === 'string' ? JSON.parse(msg) : msg

        msg[keys] = value

        Object.keys(msg).forEach((item) => {
            if (!msg[item]) {
                delete msg[item]
            }
        })

        msg.length = Object.keys(msg).length - 1

        uni.setStorageSync(msgkey, JSON.stringify(msg))
    },

    getUnReadMsg() {
        const userId = uni.getStorageSync('userInfo').id

        if (!userId) {
            return
        }

        const msgkey = `unReadMsg-${userId}`

        let msg = uni.getStorageSync(msgkey) || {}

        msg = typeof msg === 'string' ? JSON.parse(msg) : msg

        msg.length = Object.keys(msg).length - 1

        return msg
    },

    handleMessage(MsgData) {
        const {
            type,
            msg: Msg
        } = MsgData

        const tempData = JSON.parse(JSON.stringify(MsgData))

        // 获取用户id
        const userId = uni.getStorageSync('userInfo').id

        if (!userId) {
            return
        }


        let msgKey = 'gMsgList' + '-' + userId
        let msg = Msg || []


        // 转化msg格式
        if (type === 'chat') {
            msg = [MsgData]
        }

        if (type === 'offline_chat') {
            msg = msg.map((item) => {
                return {
                    ...tempData,
                    msg: item,
                    type: 'chat'
                }
            })
        }


        msg.forEach((item) => {
            const {
                from,
                to,
                groupType
            } = item.msg

            let toUSer = from === userId ? to : from

            if (groupType) {
                // 判断是群个人还是群
                if (isNaN(to)) {
                    toUSer = groupType
                } else if (groupType.includes('999_')) {
                    toUSer = '999_' + '_'+toUSer
                } else {
                    toUSer = groupType + '_' + toUSer
                }
            }

            const msgKeys = msgKey + '-' + toUSer

            // 储存未读消息
            this.handleUnReadMsg(msgKeys, true)

            let msgList = uni.getStorageSync(msgKeys) || []
            msgList = typeof msgList === 'string' ? JSON.parse(msgList) : msgList

            if (!Array.isArray(msgList)) {
                msgList = [item]
            } else {
                msgList.push(item)

                if (msgList.length >= 1000) {
                    msgList.unshift()
                }
            }

            if (type === 'offline_chat') {

                const msgSet = new Set(msgList.map((item) => JSON.stringify(item)))
                msgList = [...msgSet].map((item) => JSON.parse(item))
                // 将offline chat 排序
                msgList.sort((a, b) => b.sendTime - a.sendTime)


            }

            uni.setStorageSync(msgKeys, JSON.stringify(msgList))
        })


    },


    getMessage(msgKey) {
        const userId = uni.getStorageSync('userInfo').id

        if (!userId) {
            return
        }

     

        let msgList = uni.getStorageSync(msgKey) || {}

        return typeof msgList === 'string' ? JSON.parse(msgList) : msgList
    }
}
